package com.leetcode.string.demo4;

import java.util.Objects;

/**
 * @Author Zan
 * @Create 2024/6/3 9:04
 * @ClassName: Test
 * @Description : https://leetcode.cn/problems/reverse-words-in-a-string/description/  反转字符串中的单词
 */
public class Test {
    public static void main(String[] args) {
        String s = "  hello world  ";
        Solution solution = new Solution();
        String s1 = solution.reverseWords(s);
        System.out.println(s1);
    }
}

class Solution {
    public String reverseWords(String s) {
        String[] arr = s.split(" ");
        // 从 i - 1开始遍历输出组合
        StringBuffer sb = new StringBuffer();
        for (int j = arr.length - 1; j >= 0; j--) {
            if (!("".equals(arr[j]))) {
                sb.append(arr[j].trim());
                if (j != 0) {
                    sb.append(" ");
                }
            }
        }
        if (sb.substring(sb.length() - 1).equals(" ")) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}